import * as vscode from "vscode";
import { Logger } from "../../../src/logger/Logger";
import * as fs from 'fs';
import { ProxyService } from "../../../src/services/proxyService";

export async function docLinter(context: vscode.ExtensionContext, webview: vscode.Webview, ...args: any[]) {
    const formdata = new FormData();

      // 片段扫描
      if (args.length == 1) {
        Logger.log('Fragment check');
        const selectText = getFragment();
        if (!selectText || selectText.trim() === "") {
          vscode.window.showErrorMessage("请先选中要检查的文本片段");
          Logger.error("Fragment check error: No text selected");
          return;
        }
        const mdPath: string = args[0].fsPath || "";
        if (!mdPath.endsWith(".md")) {
          vscode.window.showErrorMessage(`Fragment check error, selected file is not a markdown file ${mdPath}`);
          Logger.error(`Fragment check error, selected file is not a markdown file ${mdPath}`)
          return;
        }
        const pathList: string[] = [mdPath]
        
        formdata.append("fullPath", pathList.join(","));
        for (const item of pathList) {
          const list = item.split("\\");
          const content = fs.readFileSync(item);
          formdata.append("files", new Blob([content]), list[list.length - 1]);
        }
        formdata.append("fragment", selectText);
      } else { // 文件扫描
        const list = args[1];
        const pathList: string[] = [];
        for (const item of list) {
          item.fsPath.endsWith(".md") ? pathList.push(item.fsPath) : pathList.push(...getMarkdownPath(item.fsPath));
        }

        formdata.append("fullPath", pathList.join(","));
        for (const item of pathList) {
          const list = item.split("\\");
          const content = fs.readFileSync(item);
          formdata.append("files", new Blob([content]), list[list.length - 1]);
        }
      }

      const url = `/api/aiService/file/check`;
      const res = await ProxyService.getInstance(context).post(url, formdata);
      if (res.success) {
        webview.postMessage({
            type: "createCheckTask",
            data: true,
          });
          Logger.log('Create task successful')
      } else {
        webview.postMessage({
            type: "createCheckTask",
            data: false,
          });
          Logger.error(`Create task failed: ${res.message}`)
      }
}


const getMarkdownPath = (dir: string): string[] => {
    const set = new Set<string>();
    const dirList = fs.readdirSync(dir);
    for (const item of dirList) {
      const curPath: string = `${dir}\\${item}`;
      const obj = fs.lstatSync(curPath);
      if (obj.isDirectory()) {
        const list = getMarkdownPath(curPath);
        for (const childPath of list) {
          set.add(childPath);
        }
      } else {
        if (curPath.endsWith(".md")) {
          set.add(curPath);
        }
      }
    }
    return Array.from(set);
  };

const getFragment = () => {
    const editor = vscode.window.activeTextEditor;
      let selectText: string = "";
      if (editor) {
        const text = editor.document.getText();
        // 兼容所有换行符类型：\r\n (Windows), \n (Unix), \r (Old Mac)
        const list = text.split(/\r\n|\n|\r/);
        const { start, end }: any = editor.selection;
        const startLine = list[start.line];
        const endLine = list[end.line];
        let textList: string[] = [];
        if (end.line === start.line) {
          textList.push(startLine.slice(start.character, end.character));
        } else if (end.line - start.line === 1) {
          textList.push(startLine.slice(start.character, startLine.length));
          textList.push(endLine.slice(0, end.character + 1));
        } else {
          textList.push(startLine.slice(start.character, startLine.length));
          const temp = list.slice(start.line + 1, end.line);
          textList = [...textList, ...temp];
          textList.push(endLine.slice(0, end.character + 1));
        }
        // 使用文档的原始换行符类型进行连接
        const eol = editor.document.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
        selectText = textList.join(eol);
      }
      return selectText;
  }